import logging

import pandas
import xlrd
import xlsxwriter
import xlwt
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from openpyxl.descriptors import excel
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from xlwt.compat import xrange
from backend.common.api_response import JsonResponse
from backend.common.common import record_dynamic
from backend.common.common_db import Interface
from backend.models import Lyzd_Interface, Lyzd_Interface_Param, Lyzd_Interface_Header, Lyzd_Interface_Case, \
    Lyzd_Interface_Case_Param, Lyzd_Interface_Case_Check, Sys_Project, Sys_Model
from backend.serializers import Sys_InterfaceSerializer, Sys_CaseSerializer, Lyzd_InterfaceCase_ActionSerializer, \
    Sys_CaseParamSerializer, Sys_CaseCheckSerializer, Lyzd_InterfaceParamSerializer

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。


class CGCaseExcleImport(APIView): #CGCaseExcleImport
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def post(self, request):
        try:

            print("导入常规校验用例")
            # p_file_list = request.FILES.getlist("file", None)
            # print(p_file_list)

            """
                上传报表
    
                :param request:
                :return:
                """

            # 获取文件
            print(1)
            p_file_list = request.FILES.get('file')
            print(p_file_list)
            print(2)

            # 报告存储路径
            path = 'backend/case/upload/' + p_file_list.name
            print(path)

            # 1.直接转化为DataFrame
            file_df = pandas.read_excel(p_file_list)

            # 数据处理

            # DataFrame保存为xlsx
            file_df.to_excel(path, index=False, header=None, float_format='%.2f')
            print(4)
            print(5)

        # # 2。直接保存上传的文件
        # handle_uploaded_file(request.FILES['file'], path)




            # x=p_file_list[0].read()
            #
            # book = xlrd.open_workbook(file_contents=x, on_demand=True)
            # print(book)
            # wbk = xlwt.Workbook()
            # print(1)
            # wb = excel.Workbooks.Open(p_file_list[0])
            # print(2)
            # print(wb)


            # def addEXcel():
            #     wbk = xlwt.Workbook()
            #     sheet = wbk.add_sheet('项目一览表', cell_overwrite_ok=True)
            #     for ifs in range(0, len(fields)):
            #         col = fields[ifs][0]
            #         fields_replace = fields_dict[col]
            #         sheet.write(0, ifs, fields_replace)
            #     ics = 1
            #     jcs = 0
            #     value_list = list(content.keys())
            #     value_list.sort()
            #     for ics in range(1, len(results) + 1):
            #         for jcs in range(0, len(fields)):
            #             replace_value(value_list, jcs, ics, sheet)
            #
            #     tz = pytz.timezone('Asia/Shanghai')
            #     start_time = datetime.datetime.now(tz)
            #
            #     format_start_time = start_time.strftime('%Y%m%d%H%M%S')
            #     # print(format_start_time)
            #     excelName = '项目管理表一览' + str(format_start_time) + '.xls'
            #     # print(excelName)
            #
            #     wbk.save(excelName)
            #     cursor.close()
            #     return excelName

            # def makefile(pathScriptName, content):
            #     f = open(pathScriptName, 'w+', encoding="utf-8")
            #     f.write(content)
            #     f.close()

            # aa = p_file_list[0]
            # bb = p_file_list[0]
            # x = p_file_list[0].read()
            # case_store_to(x)
            # print('aaaa')
            #check_resultlist = case_excel_check(x)  # 解析检查文件内容bing
            # # check_resultlist=excel_check("导入模板1(1).xlsx")#解析检查文件内容bing
            # print(check_resultlist)
            # print(check_resultlist.__len__())

            # if check_resultlist.__len__() != 0:  # 校验报错
            #     return JsonResponse(code="999997", data=check_resultlist, msg="校验失败")
            #
            # else:  # 正常
            return JsonResponse(code="999999", msg="导入成功")
        except Exception as e:
            return JsonResponse(code="999998", msg="导入失败")
